package com.binance.assetservice.data.configs;

import com.alibaba.fastjson.JSON;
import com.binance.master.data.DBConfig;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.sql.SQLException;


/**
 * 直连写模式，不走 sharding-jdbc，不走读写分离（用于生成tranId的场景）
 */
@Log4j2
@Configuration
@PropertySource("classpath:direct/db-${spring.profiles.active}.properties")
public class DirectDBConfig extends DBConfig {

    @Bean(name = "directWriteDataSource")
    @Primary
    @Override
    public DataSource dataSource() throws SQLException {
        String prefix = "old.hikaricp.data.write";
        HikariConfig config = new HikariConfig();
        config.setPoolName(this.env.getProperty(prefix + ".poolName", String.class));
        config.setDriverClassName(this.env.getProperty(prefix + ".driverClassName", String.class));
        config.setJdbcUrl(this.env.getProperty(prefix + ".jdbcUrl", String.class));
        config.setUsername(this.env.getProperty(prefix + ".username", String.class));
        config.setPassword(this.env.getProperty(prefix + ".password", String.class));
        config.setReadOnly(this.env.getProperty(prefix + ".readOnly", Boolean.class));
        config.setConnectionTimeout(this.env.getProperty(prefix + ".connectionTimeout", Long.class));
        config.setIdleTimeout(this.env.getProperty(prefix + ".idleTimeout", Long.class));
        config.setMaxLifetime(this.env.getProperty(prefix + ".maxLifetime", Long.class));
        config.setMaximumPoolSize(this.env.getProperty(prefix + ".maximumPoolSize", Integer.class));
        config.setMinimumIdle(this.env.getProperty(prefix + ".minimumIdle", Integer.class));
        log.info("DirectDBConfig: {}", JSON.toJSONString(config));
        return new HikariDataSource(config);
    }

//    @Autowired
//    public DataSourceTransactionManager transactionManager(@Qualifier("directWriteDataSource") DataSource dataSource) {
//        return null;
//    }
//
//    @Autowired
//    public SqlSessionFactory sqlSessionFactory(@Qualifier("directWriteDataSource") DataSource dataSource) throws Exception {
//        return null;
//    }

    @Primary
    @Bean(name = "directWriteJdbcTemplate")
    public JdbcTemplate directWriteJdbcTemplate(@Qualifier("directWriteDataSource") DataSource dataSource) throws Exception {
        return  new JdbcTemplate(dataSource);
    }

}
